//
//  KZPronounceTestView.m
//  听说弱点强化训练
//
//  Created by 朱凯 on 2018/10/26.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "KZPronounceTestView.h"

#import "KZPronounceNetApi.h"

// view
#import "KZAudioPlayOrRecordView.h"         // 播放和录制时间动效图
#import "KZShadowButton.h"                  // 阴影按钮
#import "KZVideoWindowPlayerView.h"         // 视图


#import "KZTimeCountDownView.h"             // 倒计时
#import "KZEvaluateResultView.h"            // 结果
#import "KZLetterCardView.h"                // 单词卡片

// tool
#import "BKAudioPlayer.h"                   // 音视频播放
#import "KYTestEngine.h"                    // 口语评测


@implementation KZPronounceTestView
{
    BOOL                    _isPass;
    NSInteger               _time;
    NSTimer                 *_timer;
    dispatch_block_t        _playAudioTask;
    
    BKAudioPlayer           *_audioPlayer;
    
    NSString                *_recordResult;             // 首次录音结果
    NSString                *_recordRepeatResult;       // 复读录音结果
    
    // 所有状态均存在
    KZLetterCardView        *_letterCardView;           // 单词卡片
    
    // 1.听标准发音
    UIView                  *_status1View;              // 状态1的视图，方便隐藏，后面也一样
    KZTimeCountDownView     *_voicePlayView;            // 播放音频
    
    // 2.自己发音，复读三遍
    UIView                  *_status2View;
    UILabel                 *_status2NoteLabel;         // 请按下面话咪开始复读
    KZTimeCountDownView     *_recordingView;            // 录音中
    
    // 3.复读一遍
    UIView                  *_status3View;
    UILabel                 *_status3NoteLabel;         // 复读三遍
    KZTimeCountDownView     *_recordingAgainView;       // 录音中
    
    // 4.系统评测
    UIView                  *_status4View;
    UILabel                 *_status4NoteLabel;         // 系统正在给您评测，请稍候
    UIImageView             *_evaluatingView;           // 评测中
    
    // 5.1.评测合格，直接下一个词汇
    UIView                  *_status5_1View;
    KZEvaluateResultView    *_successView;
    
    // 5.2.1首次不合格，要求再次复读一次，再复读用status3的视图，并修改noteLabel的文案（改为正在复读一遍）
    UIView                  *_status5_2View;
    KZEvaluateResultView    *_failureView;
    
    
    // 5.2.2再次不合格，显示发音图解视频和不合格字样，并在底部显示再“重新训练”和“下一个”2个按钮
    UIView                  *_status6View;              //
    UIButton                *_repeatButton;            // 重新训练
    UIButton                *_coursewareButton;         // 课件按钮：显示课件解析
    UIButton                *_nextButton;               // 下一个
    
    NSString                *_videoUrl;

}

- (void)dealloc {
    
    NSLog(@"销毁了");
}

- (instancetype)init {
    if (self = [super init]) {

        _audioPlayer = [BKAudioPlayer new];
        _isPauseAtRecording = false;
    }
    return self;
}
- (void)setupUI {
    
    _letterCardView = [KZLetterCardView new];
    [_letterCardView addTarget:self action:@selector(playAudio) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_letterCardView];
    [_letterCardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(H(30));
        make.left.mas_equalTo(W(10));
        make.right.mas_equalTo(W(-10));
        make.height.equalTo(_letterCardView.mas_width).multipliedBy(200.0/327);
    }];
}
// 1.听标准发音
- (void)setupStatus1View {
    
    _status1View = [UIView new];
    [self addSubview:_status1View];
    [_status1View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(self.mas_centerY).multipliedBy(1.2);
        make.bottom.equalTo(@0);
    }];
    
    _voicePlayView = [[KZTimeCountDownView alloc] initWithContentType:KZTimeCountDownContentTypePlayVoice];
    [_status1View addSubview:_voicePlayView];
    [_voicePlayView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(W(-40));
        make.width.height.mas_equalTo(W(100));
        make.centerX.equalTo(_status1View);
    }];
}

// 2.自己发音，复读三遍
- (void)setupStatus2View {
    
    _status2View = [UIView new];
    _status2View.hidden = true;
    [self addSubview:_status2View];
    [_status2View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_status1View);
    }];
    
    _recordingView = [[KZTimeCountDownView alloc] initWithContentType:KZTimeCountDownContentTypeRecordingFirst];
    [_status2View addSubview:_recordingView];
    [_recordingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_voicePlayView);
    }];
    
    _status2NoteLabel = [[UILabel alloc] init];
    _status2NoteLabel.adjustsFontSizeToFitWidth = true;
    _status2NoteLabel.numberOfLines = 1;
    _status2NoteLabel.text = @"请复读3遍...";
    _status2NoteLabel.font = FONT(14);
    _status2NoteLabel.textAlignment = NSTextAlignmentCenter;
    _status2NoteLabel.textColor = [UIColor orangeColor];
    [_status2View addSubview:_status2NoteLabel];
    [_status2NoteLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(@0);
        make.top.equalTo(_recordingView.mas_bottom);
        make.bottom.equalTo(@0);
    }];
}

// 3.复读1遍
- (void)setupStatus3View {
    
    _status3View = [UIView new];
    _status3View.hidden = true;
    [self addSubview:_status3View];
    [_status3View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_status1View);
    }];
    
    _recordingAgainView = [[KZTimeCountDownView alloc] initWithContentType:KZTimeCountDownContentTypeRecordingAgain];
    [_status3View addSubview:_recordingAgainView];
    [_recordingAgainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_voicePlayView);
    }];
    
    
    _status3NoteLabel = [[UILabel alloc] init];
    _status3NoteLabel.adjustsFontSizeToFitWidth = true;
    _status3NoteLabel.numberOfLines = 1;
    _status3NoteLabel.text = @"请复读1遍...";
    _status3NoteLabel.font = FONT(14);
    _status3NoteLabel.textAlignment = NSTextAlignmentCenter;
    _status3NoteLabel.textColor = [UIColor orangeColor];
    [_status3View addSubview:_status3NoteLabel];
    [_status3NoteLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(@0);
        make.top.equalTo(_recordingAgainView.mas_bottom);
        make.bottom.equalTo(@0);
    }];
}
// 4.系统评测
- (void)setupStatus4View {
    
    _status4View = [UIView new];
    _status4View.hidden = true;
    [self addSubview:_status4View];
    [_status4View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_status1View);
    }];
    
    _evaluatingView = [UIImageView new];
    [_evaluatingView gif:@"__4"];
    [_status4View addSubview:_evaluatingView];
    [_evaluatingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_voicePlayView);
    }];
    
    _status4NoteLabel = [[UILabel alloc] init];
    _status4NoteLabel.adjustsFontSizeToFitWidth = true;
    _status4NoteLabel.numberOfLines = 1;
    _status4NoteLabel.text = @"评判中...";
    _status4NoteLabel.font = FONT(14);
    _status4NoteLabel.textAlignment = NSTextAlignmentCenter;
    _status4NoteLabel.textColor = [UIColor orangeColor];
    [_status4View addSubview:_status4NoteLabel];
    [_status4NoteLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(@0);
        make.top.equalTo(_evaluatingView.mas_bottom);
        make.bottom.equalTo(@0);
    }];
}
// 5.1.评测合格，直接下一个词汇
- (void)setupStatus5_1View {
    
    _status5_1View = [UIView new];
    _status5_1View.hidden = true;
    [self addSubview:_status5_1View];
    [_status5_1View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_status1View);
    }];
    
    _successView = [[KZEvaluateResultView alloc] initWithStatus:true];;
    [_status5_1View addSubview:_successView];
    [_successView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_voicePlayView);
    }];
    
}
// 5.2.首次不合格，要求再次复读一次
- (void)setupStatus5_2View {
    
    _status5_2View = [UIView new];
    _status5_2View.hidden = true;
    [self addSubview:_status5_2View];
    [_status5_2View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_status1View);
    }];
    
    _failureView = [[KZEvaluateResultView alloc] initWithStatus:false];;
    [_status5_2View addSubview:_failureView];
    [_failureView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_voicePlayView);
    }];
    
}

// 6再次不合格，显示发音图解视频和不合格字样，并在底部显示再“重新训练”和“下一个”2个按钮
- (void)setupStatus6View {
    
    _status6View = [UIView new];
    _status6View.hidden = true;
    [self addSubview:_status6View];
    [_status6View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_status1View);
    }];
    
    UIView *coursewareView = [UIView new];
    [_status6View addSubview:coursewareView];
    [coursewareView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_voicePlayView);
    }];
    coursewareView.layer.cornerRadius = W(50);
    coursewareView.layer.masksToBounds = true;
    // 渐变图层
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.bounds = CGRectMake(0, 0, W(100), W(100));
    gradientLayer.position = CGPointMake(W(50), W(50));
    gradientLayer.colors = @[
                             (__bridge id)kzRGBA(254, 205, 98, 1).CGColor,
                             (__bridge id)kzRGBA(255, 149, 0, 1).CGColor,
                             ];
    [coursewareView.layer insertSublayer:gradientLayer atIndex:0];
    
    UIView *shadowView = [UIView new];
    shadowView.backgroundColor = UIColor.whiteColor;
    shadowView.layer.cornerRadius = W(50);
    [_status6View insertSubview:shadowView belowSubview:coursewareView];
    [shadowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(coursewareView);
    }];
    shadowView.layer.shadowOffset = CGSizeMake(0, 0);
    shadowView.layer.shadowRadius = 15;
    shadowView.layer.shadowOpacity = 0.6;
    shadowView.layer.shadowColor = kzRGBA(254, 205, 98, 1).CGColor;
    
    _coursewareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_coursewareButton setImage:[UIImage imageNamed:@"kz-视频图解"] forState:UIControlStateNormal];
    [_coursewareButton addTarget:self action:@selector(playVideo) forControlEvents:UIControlEventTouchUpInside];
    [coursewareView addSubview:_coursewareButton];
    [_coursewareButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(coursewareView);
    }];
    
    
    
    
    _repeatButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _repeatButton.layer.cornerRadius = W(25);
    _repeatButton.layer.masksToBounds = true;
    _repeatButton.layer.borderColor = KZThemeColor2.CGColor;
    _repeatButton.layer.borderWidth = 1;
    [_repeatButton setImage:[UIImage imageNamed:@"kz-重复"] forState:UIControlStateNormal];
    [_repeatButton addTarget:self action:@selector(repeat) forControlEvents:UIControlEventTouchUpInside];
    [_status6View addSubview:_repeatButton];
    [_repeatButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_status6View).multipliedBy(0.4);
        make.centerY.equalTo(_coursewareButton);
        make.width.height.mas_equalTo(W(50));
    }];
    UIView *shadowView2 = [UIView new];
    shadowView2.backgroundColor = UIColor.whiteColor;
    shadowView2.layer.cornerRadius = W(25);
    [_status6View insertSubview:shadowView2 belowSubview:_repeatButton];
    [shadowView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_repeatButton);
    }];
    shadowView2.layer.shadowOffset = CGSizeMake(0, 0);
    shadowView2.layer.shadowRadius = 5;
    shadowView2.layer.shadowOpacity = 0.6;
    shadowView2.layer.shadowColor = KZThemeColor2.CGColor;
    
    
    
    UIView *nextView = [UIView new];
    [_status6View addSubview:nextView];
    [nextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_status6View).multipliedBy(1.6);
        make.width.height.centerY.equalTo(_repeatButton);
    }];
    nextView.layer.cornerRadius = W(25);
    nextView.layer.masksToBounds = true;
    // 渐变图层
    CAGradientLayer *gradientLayer2 = [CAGradientLayer layer];
    gradientLayer2.bounds = CGRectMake(0, 0, W(50), W(50));
    gradientLayer2.position = CGPointMake(W(25), W(25));
    gradientLayer2.colors = @[
                              (__bridge id)kzRGBA(11, 175, 251, 1).CGColor,
                              (__bridge id)kzRGBA(71, 204, 255, 1).CGColor,
                              ];
    [nextView.layer insertSublayer:gradientLayer2 atIndex:0];
    
    UIView *shadowView3 = [UIView new];
    shadowView3.backgroundColor = UIColor.whiteColor;
    shadowView3.layer.cornerRadius = W(25);
    [_status6View insertSubview:shadowView3 belowSubview:nextView];
    [shadowView3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(nextView);
    }];
    shadowView3.layer.shadowOffset = CGSizeMake(0, 0);
    shadowView3.layer.shadowRadius = 5;
    shadowView3.layer.shadowOpacity = 0.6;
    shadowView3.layer.shadowColor = kzRGBA(11, 175, 251, 1).CGColor;
    
    _nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_nextButton setImage:[UIImage imageNamed:@"kz-下一个"] forState:UIControlStateNormal];
    
    [_nextButton addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    [nextView addSubview:_nextButton];
    [_nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(nextView);
    }];
    
    
}

#pragma mark - setter
- (void)setModel:(KZPronounceDetailModel *)model {
    
    _model = model;
    
    KZPronounceNetApi *api = [KZPronounceNetApi new];
    
    api.requestParam = @{@"DictString": [@{@"knowledge": _model.PhoneticSymbolID,
                                           @"stageNo":KGetUserDefaults(@"TestLayer"),
                                           @"schoolId":DR_UserInfo.SchoolID,
                                           @"stuId":DR_UserInfo.UserID,
                                           } yy_modelToJSONString]};
    [api getEngLetterAndPhone:^ (NSDictionary *dic){
        _videoUrl = dic[@"VedioPath"];
    } failuer:^(NSString *error) {
        
    }];
    
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    [self setupUI];
    [self setupStatus1View];
    [self setupStatus2View];
    [self setupStatus3View];
    [self setupStatus4View];
    [self setupStatus5_1View];
    [self setupStatus5_2View];
    [self setupStatus6View];
    
    // 开始测试
    [self beginTest];
}



#pragma mark - 定时器和方法
// 开始测试，创建定时器
- (void)beginTest {
    
    _recordResult = nil;
    _recordRepeatResult = nil;
    _time = 0;
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction:) userInfo:nil repeats:true];
    
}
- (void)timerAction:(NSTimer *)timer {
    
    _time ++;
    
    if (_time >= 10 && _time <= 40) {
        
        _voicePlayView.time = (_time - 10)/10.0;
    } else if (_time >= 40 && _time <= 90) {
        
        _recordingView.time = (_time - 40)/10.0;
    } else if (_time >= 130 && _time <= 160) {
        
        _recordingAgainView.time = (_time - 130)/10.0;
    }
    
    // 1.准备播放 1
    if (_time == 10) {
        [self _playAudio];
    }
    // 2.播放3秒后，关闭音频，并开启录音 1+3=4
    else if (_time == 40) {
        [self _closeAudio];
    }
    // 3.录音5秒后，跳转到评测界面 4+5=9
    else if (_time == 90) {
        [self transition:_status2View toView:_status4View];
    }
    // 在评测界面停留2秒后，显示录音结果 9+2=11
    else if (_time == 110) {
        
        [[KYTestEngine sharedInstance] stopEngine];
        if (_recordResult == nil) {
            _time -= 1;
            return;
        }
        [self analyzeRecordResult];
    }
    // 2秒用于显示结果：通过或未通过 11+2=13
    else if (_time == 130) {
        if (_isPass) {
            [_timer invalidate];
            _timer = nil;
            if (_nextBlock) {
                _nextBlock();
            }
        } else {
            [self _prepareRecord2];
        }
    }
    // 第二次检测，录音三秒，跳转到评测界面 13+3=16
    else if (_time == 160) {
        [self transition:_status3View toView:_status4View];
    }
    // 在评测界面停留2秒后，显示录音结果 16+2=18
    else if (_time == 180) {
        [[KYTestEngine sharedInstance] stopEngine];
        if (_recordRepeatResult == nil) {
            _time -= 1;
            return;
        }
        [self analyzeRecordRepeatResult];
    }
    // 2秒用于显示结果：通过或未通过 18+2=20
    else if (_time == 200) {
        [self transition:_status5_1View toView:_status6View];
        [self transition:_status5_2View toView:_status6View];
        [_timer invalidate];
        _timer = nil;
    }
    
}
// 开始播放音频
- (void)_playAudio {
    
    // 正在播放中，不播放
    if (_audioPlayer.player.status == MAudioStatePlaying) {
        return;
    }
    NSString *url = _model.AudioPath;
    [_audioPlayer playerUrl:[NSURL URLWithString:url] seekTotime:0 rateValue:1];
    [_audioPlayer playerPlay];
}
// 关闭音频，并准备开始录音
- (void)_closeAudio {
    
    [self _prepareRecord];
    
    [_audioPlayer playerPaused];
    [_audioPlayer closePlayer];
    
}

// 分析录音结果
- (void)analyzeRecordResult {
    
    NSString *testResult = _recordResult;
    NSLog(@"%@", testResult);
    NSData *data = [testResult dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    NSInteger confidence = [dic[@"result"][@"overall"] integerValue];
    
    // 录音后显示文本
    [_letterCardView flip: _model.PhoneticSymbolDes];
    
    if (confidence > LS_System.pronounceScore) {
        [self _pass:confidence];
    } else {
        [self _nopass1:confidence];
    }
}
// 分析复读录音结果
- (void)analyzeRecordRepeatResult {
    
    NSString *testResult = _recordRepeatResult;
    NSLog(@"%@", testResult);
    NSData *data = [testResult dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    NSInteger confidence = [dic[@"result"][@"overall"] integerValue];
    if (confidence > LS_System.pronounceScore) {
        // 第二次检测通过
        [self _pass2];
    } else {
        // 第二次不通过
        [self _nopass2];
    }
}

// 通关
- (void)_pass:(NSInteger)score {
    
    _isPass = true;
    _model.IsPassed = @"1";
    _model.UpdateTime = [NSDate date];
    _model.Score = @(score);
    [self transition:_status4View toView:_status5_1View];
    if (_successStayBlock) {
        _successStayBlock();
    }
    
    LSSoundPlayer *player = [[LSSoundPlayer alloc] initWithSound:KZSoundType_correct];
    self.soundPlayer = player;
}

- (void)_pass2 {
    
    [self transition:_status4View toView:_status5_1View];
    
    LSSoundPlayer *player = [[LSSoundPlayer alloc] initWithSound:KZSoundType_correct];
    self.soundPlayer = player;
}
// 第1次未通过
- (void)_nopass1:(NSInteger)score {
    
    _isPass = false;
    _model.IsPassed = @"0";
    _model.UpdateTime = [NSDate date];
    _model.Score = @(score);
    [self transition:_status4View toView:_status5_2View];
    if (_failureStayBlock) {
        _failureStayBlock();
    }
    
    LSSoundPlayer *player = [[LSSoundPlayer alloc] initWithSound:KZSoundType_wrong];
    self.soundPlayer = player;

}
// 第2次未通过
- (void)_nopass2 {
    
    [self transition:_status4View toView:_status5_2View];
    
    LSSoundPlayer *player = [[LSSoundPlayer alloc] initWithSound:KZSoundType_wrong];
    self.soundPlayer = player;

}
// 第一次录音
- (void)_prepareRecord {
    
    [self transition:_status1View toView:_status2View];
    
    // 开始评测，倒计时5秒
    KYTestConfig *config = [[KYTestConfig alloc] init];
    config.coreType = KYTestType_Sentence;
    config.refText = [NSString stringWithFormat:@"%@ %@ %@", _model.PhoneticSymbol, _model.PhoneticSymbol, _model.PhoneticSymbol];
    config.phonemeOption = KYPhonemeOption_KK;
    config.audioType = @"wav";
    config.sampleRate = 16000;
    config.sampleBytes = 2;
    config.soundIntensityEnable = true;
    [[KYTestEngine sharedInstance] startEngineWithTestConfig:config result:^(NSString *testResult) {
        
        if ([testResult rangeOfString:@"sound_intensity"].length > 0) {  //音强回调
            NSError *error;
            NSData *rdata = [testResult dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:&error];
            CGFloat soundIntensity = [[resultDic objectForKey:@"sound_intensity"] floatValue];
            NSLog(@"音量：%f",soundIntensity/10.0f);
            _recordingView.recordingView.percent = soundIntensity/10.0f;
        } else {
            _recordResult = testResult;
        }
    }];
    
}
// 第二次录音
- (void)_prepareRecord2 {
    
    _status3NoteLabel.text = @"请复读1遍...";
    [self transition:_status5_2View toView:_status3View];
    [self transition:_status6View toView:_status3View];
    
    // 复读一遍
    KYTestConfig *config = [[KYTestConfig alloc] init];
    config.coreType = KYTestType_Word;
    config.refText = [NSString stringWithFormat:@"%@", _model.PhoneticSymbol];
    config.phonemeOption = KYPhonemeOption_KK;
    config.audioType = @"wav";
    config.sampleRate = 16000;
    config.sampleBytes = 2;
    config.soundIntensityEnable = true;
    [[KYTestEngine sharedInstance] startEngineWithTestConfig:config result:^(NSString *testResult) {
        
        if ([testResult rangeOfString:@"sound_intensity"].length > 0) {  //音强回调
            NSError *error;
            NSData *rdata = [testResult dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:&error];
            CGFloat soundIntensity = [[resultDic objectForKey:@"sound_intensity"] floatValue];
            NSLog(@"音量：%f",soundIntensity/10.0f);
            _recordingAgainView.recordingView.percent = soundIntensity/10.0f;
        } else {
            _recordRepeatResult = testResult;
        }
    }];
}

#pragma mark - 事件
// 播放音频
- (void)playAudio {
    
    // 正在播放中，不播放
    if ([BKAudioPlayer sharedMPlayer].player.status == MAudioStatePlaying) {
        [[BKAudioPlayer sharedMPlayer] playerPaused];
        [[BKAudioPlayer sharedMPlayer] closePlayer];
    }
    
    NSString *url = _model.AudioPath;
    [[BKAudioPlayer sharedMPlayer] playerUrl:[NSURL URLWithString:url] seekTotime:0 rateValue:1];
    [[BKAudioPlayer sharedMPlayer] playerPlay];
    
}

// 重读一遍
- (void)repeat {
    
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    _recordingAgainView.time = 0;
    _time = 128;
    _recordRepeatResult = nil;
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction:) userInfo:nil repeats:true];
}
- (void)playVideo {
    
    KZVideoWindowPlayerView *view = [KZVideoWindowPlayerView new];
    view.url = _videoUrl;
    [view show];
}
- (void)nextAction {
    
    if (self.nextBlock) {
        self.nextBlock();
    }
}

#pragma mark - 辅助方法
// 状态视图转场动画
- (void)transition:(UIView *)fromView toView:(UIView *)toView {
    
    CATransition *ani = [CATransition animation];
    ani.type = kCATransitionFade;
    if (![self.layer animationForKey:@"Transition"]) {
        [self.layer addAnimation:ani forKey:@"Transition"];
    }
    fromView.hidden = true;
    toView.hidden = false;
}

// 开起一个延时任务
- (dispatch_block_t)beginBlockTask:(void(^)(void))block after:(NSTimeInterval)after {
    
    dispatch_block_t task = dispatch_block_create(DISPATCH_BLOCK_DETACHED, block);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(after * NSEC_PER_SEC)), dispatch_get_main_queue(), task);
    return task;
}

// 中途退出需要销毁定时器，播放中的音频，录音中的插件等
- (void)freeSource {
    
    if (_playAudioTask != NULL) {
        dispatch_block_cancel(_playAudioTask);
    }
    
    [_timer invalidate];
    _timer = nil;
    
    [_audioPlayer playerPaused];
    [_audioPlayer closePlayer];
    
    [[KYTestEngine sharedInstance] cancelEngine];
}

- (void)pauseSource {
    
    [_timer setFireDate:[NSDate distantFuture]];
    
    if (_time >= 40 && _time <= 90) {
        _time = 38;
        _isPauseAtRecording = true;
        [[KYTestEngine sharedInstance] cancelEngine];
    } else if (_time >= 130 && _time <= 160) {
        _time = 128;
        _isPauseAtRecording = true;
        [[KYTestEngine sharedInstance] cancelEngine];
    } else {
        _isPauseAtRecording = false;
    }
}
- (void)beginSource {
    
    [_timer setFireDate:[NSDate date]];
}


@end
